<template>
  <div class="deploy">
    <div class="cardTop">
      <!-- <div class="text1" @click="toDrill">训练模式</div>
      <div class="line"></div> -->
      <div class="text2">部署模式</div>
    </div>
    <el-card class="elCard">
      <div class="left">
        <ul class="leftUl">
          <li class="leftLi">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">基础信息</div>
          </li>
          <!-- <li class="leftLi2">
            <div class="circle">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
            <div class="text">高级配置</div>
            <div class="textBottom" @click="mouseupHandle()">
              <img :src="isCreate ? xiala2 : xiala" alt="" />
              选填
            </div>
          </li> -->
          <li class="leftLi3">
            <div class="circle3">
              <img src="../../assets/image/圆圈.svg" alt="" />
            </div>
          </li>
        </ul>
      </div>
      <div
        class="elForm"
        v-loading="loading"
        element-loading-text="极速生成中..."
        :element-loading-spinner="svg"
        element-loading-svg-view-box="-10, -10, 50, 50"
      >
        <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
          <el-form-item label="模型名" prop="cont_name">
            <el-input v-model="form.cont_name" />
          </el-form-item>
          <div class="nameText">
            请设置一个英文模型名&nbsp;
            <span class="nameTextSpan">(支持英文+数字格式)</span>
            &nbsp;方便后续的查询和使用&nbsp;~
          </div>
          <el-form-item label="选择模型" prop="model">
            <el-select v-model="form.model" placeholder="请选择一个模型">
              <el-option
                v-for="(item, index) in modelList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择镜像地址" prop="workmode">
            <el-select v-model="imageList.value" placeholder="请选择镜像地址">
              <el-option
                v-for="(item, index) in imageList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择工作环境" prop="image">
            <el-input v-model="selectedOption" />
          </el-form-item>

          <div class="echarts">
            <div id="myEcharts"></div>
          </div>

          <!-- 高级选项 -->
          <div v-if="user.role === 'level2'">
            <el-form-item label="主机端口">
              <el-input v-model="form.local_port" />
            </el-form-item>
            <el-form-item label="服务端口">
              <el-input v-model="form.server_port" />
            </el-form-item>
            <el-form-item label="工作台端口">
              <el-input v-model="form.worker_port" />
            </el-form-item>
          </div>
          <el-form-item class="elButton">
            <el-button type="primary" @click="onSubmit">创建模型</el-button>
            <el-button @click="cancel">取消创建</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElMessage,
  ElCard
} from 'element-plus'
import {
  ref,
  reactive,
  computed,
  onUnmounted,
  onMounted,
  watch,
  inject,
  nextTick
} from 'vue'
import * as echarts from 'echarts'
import { beginDeploy } from '../../api/model.js'
import { useRouter } from 'vue-router'

const user = reactive({
  role: 'level1' // 初始权限为一级
})

const router = useRouter()
const loading = ref(false)

const imageList = ref(['langport0.6', 'llama0.7'])

const workmodeList = ref(['训练模式', '推理模式'])

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 3px; fill: rgba(0, 0, 0, 0)"/>
      `

const formRef = ref(null)

const form = ref({
  cont_name: '',
  image: '',
  model: '',
  workmode: ''
})

const modelList = ref([
  'agi ui',
  'autogen',
  'bert-base-chinese',
  'ChatGLM2-6B',
  'chatglm2-6b-32k',
  'internlm-chat-7b-8k',
  'lang_output',
  'langport',
  'langport_logs',
  'LocalAI',
  'logs',
  'mambaforge',
  'ningyu-spring-15b-v1.0-fp16',
  'openbuddy-3@b-v1.3-ggml',
  'openbuddy-30b-v7.1-bf16',
  'openbuddy-7b-v4',
  'openbuddy-f-7b-v6-bf16',
  'openbuddy-ggm1-30b-v1.3',
  'openbuddy-llama2-13b-v8.1-fp16',
  'openbuddy-lamacpp-13b-v5-q5',
  'openbuddy-mistral-7b-v13.1',
  'openbuddy-openllama-13b-v7-fp16',
  'openbuddy-openllama-7b-v12-bf16',
  'openbuddy-openllama-7b-v5-fp16',
  'openbuddy-zephyr-7b-V14.1',
  'pro-langport',
  'sentence-bert',
  'snap',
  'test4newname',
  'UIE'
])

let chartInstance = null
const selectedOption = ref('')

const isHighShow = ref(false) // 高级配置显示
const isCreate = ref(false) // 下拉图片切换

const toDrill = () => {
  router.push('./create')
}

const cancel = () => {
  // router.push('./')
  user.role = 'level2' //二级权限
}

const rules = reactive({
  cont_name: [
    { required: true, message: '请输入正确的英文名字', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
      message: '英文名字格式错误 支持英文+数字',
      trigger: 'blur'
    }
  ],
  image: [
    {
      required: true,
      message: '请从下图中选择镜像地址',
      trigger: 'blur',
      validator: validateImage
    }
  ],
  model: [{ required: true, message: '请选择正确的模型', trigger: 'blur' }],
  workmode: [{ required: true, message: '请选择一个工作环境', trigger: 'blur' }]
})

// echarts选中后通过validate校验
function validateImage (rule, value, callback) {
  if (selectedOption.value) {
    // 有值时直接通过验证
    callback()
  } else {
    // 没有值时显示错误信息
    callback(new Error('请从下图中选择镜像地址'))
  }
}

function initChart () {
  const chartDom = document.getElementById('myEcharts')
  let chartInstance = echarts.init(chartDom)

  // 根据imageList数组生成series中的data数据
  const echartsDataList = workmodeList.value.map((name, index) => {
    return {
      value: Math.floor(100 / workmodeList.value.length),
      name: name
    }
  })

  // 把配置和数据放这里
  chartInstance.setOption({
    color: [
      '#37a2da',
      '#32c5e9',
      '#9fe6b8',
      '#ffdb5c',
      '#ff9f7f',
      '#fb7293',
      '#e7bcf3',
      '#8378ea'
    ],
    tooltip: {
      trigger: 'item',
      // formatter: '{a}<br/>{b}训练部署模型'
      formatter: function (params) {
        if (params.name === '训练模式') {
          // return '<div style="width: 150px; height: 80px; padding: 10px; background-color: #fff;font-size:18px">训练模式: <br/>可训练部署模型</div>'
          return `<div style="display: flex; align-items: center;">
                <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
                ${params.name}&nbsp;,&nbsp;可训练部署模型
              </div>`
        } else if (params.name === '推理模式') {
          return `<div style="display: flex; align-items: center;">
                <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
                ${params.name}&nbsp;,&nbsp;可一键部署模型
              </div>`
        }
        return ''
      }
    },
    toolbox: {
      show: true
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: '20%',
      align: 'left',
      top: 'middle',
      textStyle: {
        color: '#8C8C8C'
      },
      height: 150
    },
    series: [
      {
        name: '工作模式:',
        type: 'pie',
        radius: [0, 70],
        data: echartsDataList
        // labelLine: { // 取消echarts往外指出的小横线
        //   length: 0,
        //   length2: 0
        // }
      }
    ]
  })

  chartInstance.on('click', params => {
    selectedOption.value = params.name
  })

  window.onresize = function () {
    //自适应大小
    chartInstance.resize()
  }
}

onMounted(() => {
  initChart()
})

// 关闭echarts时销毁实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})

const onSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    loading.value = true
    let msgData = {
      imgname: selectedOption.value,
      cont_name: form.value.cont_name,
      model_path: `/nvme1/${modelList.value}`,
      // model_path: '/nvme1/ningyu',
      model_name: 'aa',
      workmode: form.workmode === '0' ? '0' : '1',
      docker_ports: '8002',
      local_ports: '8002',
      net_name: 'test4lang',
      ctrad: '21001',
      logs_path: '/nvme1/ningyu/langport_logs'
    }
    console.log('创建新容器之前提交的数据', msgData)
    beginDeploy(msgData)
      .then(res => {
        loading.value = false

        // 处理请求成功的响应
        console.log('res', res)

        ElMessage({
          showClose: true,
          message: '创建成功 训练或部署 让数据更严谨吧~',
          type: 'success'
        })
        router.push('./drill')

        if (res.msg === 'build failed') {
          ElMessage({
            showClose: true,
            message: '模型名重复 请设置一个新的模型名',
            type: 'info'
          })
        }
      })
      .catch(error => {
        loading.value = false
        // 处理请求错误
        console.error(error)
      })

    console.log('提交了表单')
  } else {
    console.log('表单数据不完整')
  }
}
</script>

<style lang="less" scoped>
.deploy {
  padding: 30px 60px 0 60px;

  .cardTop {
    margin-bottom: 30px;
    color: #27264d;
    font-size: 32px;
    opacity: 0.85;
    display: flex;

    .text1 {
      margin: 0 10px 0 5px;
    }
    .text2 {
      margin: 0 10px 0 10px;
    }
    .line {
      width: 3px; /* 设置线的宽度 */
      height: 30px; /* 设置线的高度，这里假设线的高度与父元素高度相同 */
      background-color: grey; /* 设置线的颜色 */
    }
  }
  .elCard {
    .left {
      width: 300px;
      .leftUl {
        img {
          width: 20px;
          height: 20px;
        }
        .text {
          margin-left: 15px;
          color: #27264d;
          font-weight: 500;
          font-size: 16px;
          line-height: 24px;
          letter-spacing: 0;
          opacity: 0.85;
        }

        .leftLi {
          display: flex;
          .circle {
            position: relative;
          }
          .circle::after {
            content: '';
            position: absolute;
            top: 60%;
            left: 50%;
            transform: translate(-50%, 0);
            width: 2px;
            height: 480px;
            background-color: #75b7ff;
          }
        }

        .leftLi3 {
          display: flex;
          .circle3 {
            position: relative;
            top: 455px;
            opacity: 1;
          }
        }
      }
    }
    .elForm {
      width: 1000px;

      .nameText {
        display: flex;
        color: #27264d;
        justify-content: start;
        align-items: center;
        height: 40px;
        padding: 0 0 15px 150px;
        .nameTextSpan {
          font-size: 14px;
          color: #409eff;
        }
      }

      .echarts {
        #myEcharts {
          width: 1300px;
          height: 200px;
        }
      }
      :deep(.el-select) {
        width: 100%;
      }
      .elButton {
        :deep(.el-form-item__content) {
          display: flex;
          justify-content: space-between;
          margin-top: 30px;
        }
      }
    }
  }

  :deep(.el-card__body) {
    display: flex;
  }
}
</style>
